//
//  OutpatientController.m
//  HarmonizePub
//
//  Created by rzhy on 16/8/24.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "OutpatientController.h"
#import "Config.h"
#import "UPPaymentControl.h"
#import "OutpatientTableViewCell.h"
#import "SVProgressHUD.h"
#import "Patient.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>


// 充值方式
typedef NS_ENUM(NSUInteger, RechargeMethod) {
    RechargeMethodWeChatPay = 0, // 微信支付
    RechargeMethodAliPay    = 1, // 支付宝支付
    RechargeMethodUnionPay  = 2 // 银联支付
};

@interface OutpatientController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>
{
    NSNumber *_orderId;
}
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *cardNumLabel;

@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;
@property (weak, nonatomic) IBOutlet UITextField *moneyTextField;

@property (weak, nonatomic) IBOutlet UIButton *rechargeButton;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSArray *payLists;

@property (nonatomic, assign) NSInteger rechargeMethod;
@property (assign, nonatomic) NSString * WXoiderid;

@end

@implementation OutpatientController

- (NSArray *)payLists
{
    if (_payLists == nil) {
        _payLists = [[NSArray alloc] init];
    }
    return _payLists;
}

static NSString *CellIdentifier = @"cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    Patient *patient = [Patient sharedPatient];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame: CGRectZero];
    self.title = @"门诊充值";
    self.rechargeButton.layer.cornerRadius = 5.0f;
    self.rechargeButton.layer.masksToBounds = YES;
    self.nameLabel.text = patient.name;
    self.cardNumLabel.text = patient.bindNum;

    // 加载支付方式列表
    self.payLists =[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"payList.plist" ofType:nil]];

    // 通知  微信回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backWXblock:) name:@"WX_PaySuccess" object:nil];
    // 通知  支付宝回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayCallback:) name:@"Alipay_PaySuccess" object:nil];
    
    // 获取门诊余额
    [self requireMZYE];
    
    UINib *nib = [UINib nibWithNibName:[OutpatientTableViewCell registerName] bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
}

-(void)viewWillAppear:(BOOL)animated{

    if (self.balanceLabel.text.length == 0) {
        // 获取门诊余额
        [self requireMZYE];

    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 获取门诊余额
- (void)requireMZYE
{
    NSDictionary *cooike = @{CookieVaule : [UserDefaultsTool stringForKey: XHToken]};
    Patient *patient = [Patient sharedPatient];
    NSDictionary *params = @{@"id" : @(patient.id)};
    __weak typeof(OutpatientController) *weakSelf = self;
    [HTTPSTool POSTRequestWithPath: XHMzYe  cookie: cooike params: params success:^(NSDictionary * _Nonnull JSON) {
        weakSelf.balanceLabel.text = [NSString stringWithFormat:@"￥%@", JSON[@"data"][@"amt"]];
    }];
}

#pragma mark - 前往充值
- (IBAction)rechargeEvent:(UIButton *)sender {
    NSString *moneyString = self.moneyTextField.text;
    if (!moneyString || [moneyString isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入要充值的金额!"];
    } else {
        // 发起支付
        [self startPay];
       
    }
}

#pragma mark - 发起支付
- (void)startPay
{
    if (self.rechargeMethod == RechargeMethodUnionPay) { // 银联支付
        
        [self jumpToUnionPay];
        
    }else if (self.rechargeMethod == RechargeMethodWeChatPay){ // 微信支付
        // 判断是否安装微信
        if (![WXApi isWXAppInstalled]) {
            [self setAlertViewWithMessage:@"未安装微信"];
        }else{
            [self jumpToWeixinPay];
        }
    }else if (self.rechargeMethod == RechargeMethodAliPay){ // 支付宝支付
    
        [self jumpToAliPay];
    }
    
}

#pragma mark - 微信支付
- (void)jumpToWeixinPay
{
    Patient *patient = [Patient sharedPatient];
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    // 金额, 单位分
    CGFloat money = [self.moneyTextField.text doubleValue] * 100;
//    if (self.titleType == 1) {
//        type = @"1";  // 门诊
//    }else{
//        type = @"3";  // 住院
//    }
    NSDictionary *params = @{@"amt" : @(money),
                             @"id" : @(patient.id),
                             @"type":@"1",
                             @"deviceType":@"IOS"
                             };
    [HTTPSTool POSTRequestWithPath:XHWeiXinPay cookie:cookie params:params success:^(NSDictionary * _Nonnull JSON) {
//        NSLog(@"%@",JSON);
        
        NSDictionary * dic = JSON[@"data"];
        
        // 获取orderid 留回调处理
        self.WXoiderid = [NSString stringWithFormat:@"%@",dic[@"orderId"]];
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:self.WXoiderid forKey:@"WXoiderid"];
        [defaults synchronize];
        
        PayReq *request = [[PayReq alloc] init];
        /** 商家向财付通申请的商家id */
        request.partnerId = dic[@"partnerid"];
        /** 预支付订单 */
        request.prepayId= dic[@"prepayid"];
        /** 商家根据财付通文档填写的数据和签名 */
        request.package = dic[@"package"];
        /** 随机串，防重发 */
        request.nonceStr= dic[@"noncestr"];
        /** 时间戳，防重发 */
        NSString * str = dic[@"timestamp"];
        request.timeStamp= [str intValue];
        /** 商家根据微信开放平台文档对数据做的签名 */
        request.sign= dic[@"sign"];
        /*! @brief 发送请求到微信，等待微信返回onResp
         *
         * 函数调用后，会切换到微信的界面。第三方应用程序等待微信返回onResp。微信在异步处理完成后一定会调用onResp。支持以下类型
         * SendAuthReq、SendMessageToWXReq、PayReq等。
         * @param req 具体的发送请求，在调用函数后，请自己释放。
         * @return 成功返回YES，失败返回NO。
         */
        [WXApi sendReq: request];
        
    }];
}
#pragma mark 微信回调处理
- (void)backWXblock:(NSNotification *)notion{
    Patient *patient = [Patient sharedPatient];
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSString * str = [defaults objectForKey:@"WXoiderid"];
    NSDictionary *params = @{@"id" : str};
    [SVProgressHUD show];
    __weak typeof(self) weakSelf = self;
    [HTTPSTool POST:XHWeiXinPayState params:params  cookie:cookie  success:^(NSDictionary * _Nonnull JSON) {
//        NSLog(@"%@",JSON);
        NSInteger ret = [JSON[@"ret"] integerValue];
        NSString *msg = JSON[@"msg"];
        [SVProgressHUD dismiss];
        if (ret == 2) {
            msg = [msg stringByAppendingString:@"\n是否需要刷新？"];
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示:" message:msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"刷新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf backWXblock:nil];
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:sureAction];
            [weakSelf presentViewController:alertController animated:YES completion:nil];
        } else {
            NSDictionary *data = JSON[@"data"];
            NSString *ye = data[@"ye"];
            if (ye.length)
                weakSelf.balanceLabel.text = [NSString stringWithFormat:@"¥%@", ye];
            [weakSelf setAlertViewWithMessage:msg];
        }
    } failure:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
    
}

#pragma mark - 银联支付
- (void)jumpToUnionPay
{
    Patient *patient = [Patient sharedPatient];
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    // 金额, 单位分
    CGFloat money = [self.moneyTextField.text doubleValue] * 100;
    NSDictionary *params = @{@"amt" : @(money),
                             @"id" : @(patient.id)
                             };
//    LRLog(@"params:%@", params);
    [HTTPSTool POSTRequestWithPath: XHUnionPay cookie: cookie params: params success:^(NSDictionary * _Nonnull JSON) {
        NSString *tn = JSON[@"data"][@"tn"];
        
        NSString *orderId = JSON[@"data"][@"orderId"];
        [UserDefaultsTool setObject: orderId forKey:XHUnionPayOrderId];
        // 发起支付
        if (tn != nil && tn.length > 0)
        {
            [[UPPaymentControl defaultControl] startPay: tn fromScheme:@"RZHYHarmonizePubUnionPay" mode: @"01" viewController:self];
        }
    }];
}

// 测试接口http://192.168.100.202/XhApp/ws/user/getAliPay
// http://116.62.50.113/XhApp/ws/user/getAliPay  // XHAliPay
#pragma mark - 支付宝支付
- (void)jumpToAliPay
{
//    [self setAlertViewWithMessage:XHAlertMsg];
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    CGFloat money = [self.moneyTextField.text doubleValue] * 100;
    Patient *patient = [Patient sharedPatient];
    NSDictionary *params = @{@"amt" : @(money),
                             @"id" : @(patient.id),
                             @"type" : @"1"
                             };
    [HTTPSTool POSTRequestWithPath: XHAliPay cookie: cookie params:params success:^(NSDictionary * _Nonnull JSON) {
        NSString *orderString = JSON[@"data"][@"sign"];
        _orderId = JSON[@"data"][@"orderId"];
//         LRLog(@"%@", orderString);
        if (orderString != nil) {
            //应用注册scheme
            NSString *appScheme = @"RZLJZYYPubAlipay";
            // NOTE: 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                LRLog(@"APP存在与后台时支付结果:%@",resultDic);
            }];
        }

    }];
}

#pragma mark 支付宝回调
- (void)alipayCallback:(NSNotification *)notification {
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    NSDictionary *param = @{@"id" : _orderId};
    __weak typeof(self) weakSelf = self;
    [SVProgressHUD show];
    [HTTPSTool POST:XHUserGetAliPayStatus params:param cookie:cookie success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"支付宝回调 -> JSON: %@", JSON);
        NSString *msg = JSON[@"msg"];
        NSInteger ret = [JSON[@"ret"] integerValue];
        [SVProgressHUD dismiss];
        if (ret == 2) {
            msg = [msg stringByAppendingString:@"\n是否需要刷新？"];
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示:" message:msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"刷新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf alipayCallback:nil];
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:sureAction];
            [weakSelf presentViewController:alertController animated:YES completion:nil];
        } else {
            NSDictionary *data = JSON[@"data"];
            NSString *ye = data[@"ye"];
            if (ye.length)
                weakSelf.balanceLabel.text = [NSString stringWithFormat:@"¥%@", ye];
            [weakSelf setAlertViewWithMessage:msg];
        }
    } failure:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - UITableViewDelegate/UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.payLists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    OutpatientTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    NSDictionary *dict = self.payLists[indexPath.row];
    
    cell.dict = dict;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OutpatientTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isSelected = YES;
    
    if (indexPath.row == 0) {
        self.rechargeMethod = RechargeMethodWeChatPay;
        
    }else if (indexPath.row == 1){;
        self.rechargeMethod = RechargeMethodAliPay;
        
    }else{
        self.rechargeMethod = RechargeMethodUnionPay;
    }
    [self.moneyTextField resignFirstResponder];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OutpatientTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isSelected = NO;
}

#pragma mark - AlertView
- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示:" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_moneyTextField resignFirstResponder];
}

@end
 
